import getFont from "../../../utils/getFont";

const getNewFont = (font, boldBool, italicBool) => {
    const fontObj = getFont(font);
    const newFont = [];
    if (boldBool) {
        newFont.push('bold');
    } else {
        newFont.push('normal')
    }
    if (italicBool) {
        newFont.push('italic');
    } else {
        newFont.push('normal');
    }
    newFont.push(fontObj.fontSize + 'px');
    newFont.push(fontObj.fontFamily);
    return newFont.join(' ');
}
export default {
    canUndo: true,
    execute: (context, options, isUndo) => {
        try {
            const { sheet, selections, _oldFont, fontType } = options;
            sheet.suspendPaint();
            if (isUndo) {
                selections.forEach(range => {
                    for (let row = range.row, i = 0; i < range.rowCount; i++ , row++) {
                        for (let col = range.col, j = 0; j < range.colCount; j++ , col++) {
                            const cell = sheet.getCell(row, col);
                            cell.font(_oldFont[row][col]);
                        }
                    }
                });
            } else {
                selections.forEach(range => {
                    for (let row = range.row, i = 0; i < range.rowCount; i++ , row++) {
                        for (let col = range.col, j = 0; j < range.colCount; j++ , col++) {
                            const cell = sheet.getCell(row, col);
                            const oldFont = cell.font();
                            if (!options._oldFont) {
                                options._oldFont = {};
                            }
                            if (!options._oldFont[row]) {
                                options._oldFont[row] = {};
                            }
                            options._oldFont[row][col] = oldFont;
                            const newFont = getNewFont(oldFont, fontType.bold, fontType.italic);
                            cell.font(newFont);
                        }
                    }
                });
            }
            sheet.resumePaint();

        } catch (e) {
            if(!!(window.console&&window.console.log)) {
                window.console.log(e);
            }
        }
    }
};